<template>
  <div class="correction-container flex">
    <div class="container-left">
      <div class="tool-header flex-between" v-if="!isAddingAnnotation">
        <el-popover
          width="40vw"
          trigger="click"
          placement="bottom-end"
          popper-class="correction-popper"
        >
          <div class="topic-container">
            <AssignTopic
              v-if="questionInfo"
              :index="questionInfo.questionText"
              :topic-data="questionInfo.question_detail"
              :is-show-parser="true"
              :is-similar="false"
              :is-basket="false"
            />
          </div>
          <template #reference>
            <div class="flex hover">
              原题及答案解析
              <img
                class="answer-img"
                src="@/assets/images/single-correct/analysis-normal.png"
              />
              <template v-if="isHistory && currentAnswer">
                {{ questionInfo.questionText }}:
                {{ questionInfo.question_type }}题块
                <span class="remark">
                  回评（{{ answerIndex + 1 }} /
                  {{ answerList.slice(0, historyLastIndex).length + 1 }}）
                </span>
                <span class="remark-text">
                  已评{{
                    taskInfo?.correctType == CORRECT_TYPE.ROUGH
                      ? TEACHER_CORRECT_TEXT[currentAnswer?.teacher_correct]
                      : `${currentAnswer.score}分`
                  }}
                </span>
              </template>
            </div>
          </template>
        </el-popover>
        <div class="flex">
          <div class="correct-control flex">
            <button
              class="header__button btn-continue"
              :disabled="!isHistory"
              @click="onToggleHistory('mark')"
            >
              继续阅卷
            </button>
            <button
              class="header__button btn-previous"
              :disabled="!canPreMark"
              @click="onToggleHistory('pre')"
            >
              回评上一份
            </button>
            <button
              class="header__button btn-next"
              :disabled="!canNextMark"
              @click="onToggleHistory('next')"
            >
              回评下一份
            </button>
          </div>
          <div class="correct-control img-control flex">
            <button
              @click="resetScale()"
              class="header__button btn-reset-scale"
            ></button>

            <button
              @click="zoomIn()"
              class="header__button btn-zoom-in"
            ></button>
            <button
              @click="zoomOut()"
              class="header__button btn-zoom-out"
            ></button>
            <button
              @click="rotate()"
              class="header__button btn-rotate"
            ></button>
          </div>
        </div>
      </div>
      <!-- 学生答案区域 -->
      <main class="answer-container">
        <template v-if="currentAnswer && questionInfo">
          <!-- 文本回答 -->
          <template v-if="answerType === ANSWER_TYPE.TEXT">
            <div class="answer-text">
              <div
                v-html="
                  getNormalizeData(
                    JSON.parse(currentAnswer.response || JSON.stringify([])),
                    getParseData(
                      questionInfo.itemType === QUESTION_ITEM_TYPE.BIG_ITEM
                        ? questionInfo.question_detail
                        : questionInfo.question_detail?.subproblem[0]
                    )
                  )
                "
              ></div>
            </div>
            <!-- 文本批注 -->
            <div
              class="answer-text"
              v-if="!isAddingAnnotation && currentAnswer.teacher_evaluate"
            >
              教师批注：{{ currentAnswer.teacher_evaluate }}
            </div>
            <div class="annotation-box flex-end">
              <AnnotationText
                v-if="isAddingAnnotation"
                @cancel="onToggleMark"
                @update="onUpdateText"
                :value="currentAnswer.teacher_evaluate"
              />
              <el-button
                v-else
                type="primary"
                text
                class="annotation-btn flex"
                @click="onToggleMark"
              >
                <AnnotationBtn class="img" />
                批注
              </el-button>
            </div>
          </template>
          <!-- 图片回答 -->
          <template v-else>
            <AnswerImg
              :img-url="currentAnswer.response_url"
              @update-annotation-img-url="onUpdateImg"
              :is-rotated="isRotated"
              :scale-ratio="scaleRatio"
              :history-img="currentAnswer.teacher_evaluate_url"
              :total-score="currentAnswer.set_total_score"
              :location-list="locationList"
              ref="answerImg"
            />
          </template>
        </template>
        <div v-else class="flex-column empty-paper-tips">
          <img
            src="@/assets/images/single-correct/done.png"
            :draggable="false"
          />
          <p>当前题块已批改完毕，感谢老师的辛勤付出！</p>
        </div>
      </main>
    </div>
    <ScoreBoard
      :class="{ 'score-board-disabled': !currentAnswer }"
      :show-board="!!currentAnswer"
      :title="questionInfo?.questionText"
      :correct-type="correctType"
      :total-score="currentAnswer?.set_total_score"
      :answer-type="answerType"
      @submitScore="changeScore"
      ref="scoreBoardRef"
    />
  </div>
</template>

<script setup>
import { computed, ref, watch, nextTick } from 'vue'
import { getStudentMsg } from '@/apis/single-correct/index'
import AssignTopic from '../../components/AssignTopic.vue'
import { getNormalizeData, getParseData } from '@/utils/answer'
import AnnotationBtn from '@/assets/images/assignment/annotation.svg'
import AnnotationText from '@/components/annotation/AnnotationText.vue'
import AnswerImg from './AnswerImg.vue'
import { useAuthStore } from '@/stores'
import ScoreBoard from '@/components/score-board/ScoreBoard.vue'
import {
  QUESTION_ITEM_TYPE,
  CORRECT_TYPE,
  TEACHER_CORRECT_TYPE,
  ANSWER_TYPE,
  TEACHER_CORRECT_TEXT
} from '../data'
import { postTeacherFeedBack } from '@/apis/assignment'
import { ElMessage } from 'element-plus'
import { singleCorrectMitt } from '@/utils/tools/bus'

const props = defineProps({
  taskInfo: {
    required: true
  },
  questionInfo: {
    required: true
  }
})
const correctType = computed(() => {
  return Number(props.taskInfo.correctType)
})

const locationList = computed(() =>
  JSON.parse(currentAnswer.value.correct_location || JSON.stringify([]))
)
const emit = defineEmits(['updateCurrentAnswer', 'updateQuestionList'])
const { userInfo } = useAuthStore()
const questionInfo = computed(() => props.questionInfo)
const answerList = ref([])
const answerIndex = ref(null) // 当前答案序号
const currentAnswer = computed(() => {
  let value = null
  // 当前学生的答案
  if (answerIndex.value >= 0) {
    value = answerList.value[answerIndex.value]
  }
  emit('updateCurrentAnswer', value)
  return value
})
const answerType = computed(() => {
  // 答案类型
  if (currentAnswer.value) {
    return JSON.parse(currentAnswer.value.response_url || '[]').length
      ? ANSWER_TYPE.PIC
      : ANSWER_TYPE.TEXT
  }
  return ''
})

// #批注相关
const isAddingAnnotation = ref(false) // 是否开启批注
const annotationText = ref('')
const annotationImg = ref([])
const onToggleMark = () => {
  isAddingAnnotation.value = !isAddingAnnotation.value
}
const resetAnno = () => {
  annotationImg.value = []
  annotationText.value = ''
}
const onUpdateText = value => {
  isAddingAnnotation.value = false
  annotationText.value = value
  answerList.value[answerIndex.value].teacher_evaluate = annotationText.value
}
const onUpdateImg = urls => {
  annotationImg.value = urls
}

const scoreBoardRef = ref(null)
watch(
  () => currentAnswer.value,
  () => {
    resetAnno()
    nextTick(() => {
      let score =
        correctType.value === CORRECT_TYPE.ROUGH
          ? currentAnswer.value?.teacher_correct
          : currentAnswer.value?.score
      scoreBoardRef.value.initData(score)
    })
  },
  {
    immediate: true
  }
)
const changeScore = async (score, list) => {
  // 点击打分时才会有list传入，否则为undefined
  console.log(score, list)
  await handleTeacherCorrect(score, list || [])
  if (!isHistory.value) {
    emit('updateQuestionList', true)
  }
}

// #操作图片相关
const scaleRatio = ref(1)
const isRotated = ref(false)
const answerImg = ref()
const resetScale = () => {
  scaleRatio.value = 1
  answerImg.value?.resetXY()
}
const zoomIn = () => {
  scaleRatio.value += 0.2
}
const zoomOut = () => {
  scaleRatio.value -= 0.2
}
const rotate = () => {
  isRotated.value = !isRotated.value
}

// #教师端提交题目批改
const handleTeacherCorrect = async (score, list = []) => {
  let param = {
    teacher_id: Number(userInfo.userId),
    task_id: Number(props.taskInfo.taskId),
    student_id: currentAnswer.value.student_id,
    teacher_correct: TEACHER_CORRECT_TYPE.NO_CORRECT,
    question_id: props.questionInfo.question_detail.id,

    score: -1,
    set_total_score: 0,
    teacher_evaluate: '',
    teacher_evaluate_url: [],
    correct_location: JSON.stringify([]),
    children_question_info: []
  }
  if (props.questionInfo.itemType === QUESTION_ITEM_TYPE.BIG_ITEM) {
    param = {
      ...param,
      score: correctType.value === CORRECT_TYPE.SCORE ? score : -1,
      set_total_score: currentAnswer.value.set_total_score,
      teacher_correct:
        correctType.value === CORRECT_TYPE.ROUGH
          ? score
          : TEACHER_CORRECT_TYPE.NO_CORRECT,
      teacher_evaluate: annotationText.value,
      teacher_evaluate_url: annotationImg.value,
      correct_location: JSON.stringify(list)
    }
  } else {
    let subQuestion = props.questionInfo.question_detail.subproblem[0]
    param = {
      ...param,
      children_question_info: [
        {
          question_id: subQuestion.id,
          question_type: subQuestion.type,
          teacher_evaluate: annotationText.value,
          teacher_evaluate_url: annotationImg.value,
          correct_location: JSON.stringify(list),
          set_total_score: currentAnswer.value.set_total_score,
          score: correctType.value === CORRECT_TYPE.SCORE ? score : -1,
          teacher_correct:
            correctType.value === CORRECT_TYPE.ROUGH
              ? score
              : TEACHER_CORRECT_TYPE.NO_CORRECT
        }
      ]
    }
  }
  const res = await postTeacherFeedBack(param)

  if (res.code === 1) {
    ElMessage.success('批改成功！')
    isAddingAnnotation.value = false
    getStudentMsgInfo(!isHistory.value)
  }
}

// #获取题目学生的作答
const getStudentMsgInfo = async (isUpdate = true) => {
  const questionId =
    questionInfo.value.itemType === QUESTION_ITEM_TYPE.SMALL_ITEM
      ? questionInfo.value.question_detail.subproblem[0].id
      : questionInfo.value.question_detail.id

  const res = await getStudentMsg({
    task_id: props.taskInfo.taskId,
    class_id: props.taskInfo.classId,
    question_id: questionId,
    item_type: questionInfo.value.itemType
  })
  const result = getHisOrNoAnswerList(res.data || [])
  answerList.value = [...result.finishList, ...result.waitList]
  if (isUpdate) {
    onToggleHistory('pre')
    answerIndex.value = getCorrectIndex()
    isHistory.value = false
  }
}

// #回评相关参数
// 是否能进入历史批改模式
const isHistory = ref(false) // 是否进入历史批改模式
const historyLastIndex = ref(-1) // 可以批改的历史模式下标
watch(
  () => answerList.value,
  () => {
    let correctIndex = getCorrectIndex()
    historyLastIndex.value =
      correctIndex > 0
        ? correctIndex - 1
        : getHisOrNoAnswerList(answerList.value).finishList.length ===
            answerList.value.length
          ? answerList.value.length - 1
          : -1
  }
)
// 是否能回评上一份
const canPreMark = computed(() => {
  return isHistory.value ? answerIndex.value > 0 : historyLastIndex.value >= 0
})
// 是否能回评下一份
const canNextMark = computed(() => {
  return isHistory.value ? answerIndex.value < historyLastIndex.value : false
})
// 切换回评 mark pre next
const onToggleHistory = type => {
  switch (type) {
    case 'mark':
      isHistory.value = false
      answerIndex.value = getCorrectIndex()
      break
    case 'pre':
      if (!isHistory.value) {
        answerIndex.value = historyLastIndex.value
      } else {
        answerIndex.value--
      }
      isHistory.value = true
      break
    case 'next':
      if (answerIndex.value <= historyLastIndex.value) {
        answerIndex.value++
      }
      isHistory.value = true
  }
}

// #获取可以第一个批改的下标
const getCorrectIndex = () => {
  // 找到第一个可以批改的下标
  let index = -1
  if (props.taskInfo.correctType === CORRECT_TYPE.ROUGH) {
    index = answerList.value.findIndex(
      item => item.teacher_correct == TEACHER_CORRECT_TYPE.NO_CORRECT
    )
  } else {
    index = answerList.value.findIndex(item => item.score < 0)
  }
  return index
}

// #获取批改好的和未批改学生答案列表
const getHisOrNoAnswerList = list => {
  let result = {
    finishList: [],
    waitList: []
  }
  if (props.taskInfo.correctType === CORRECT_TYPE.ROUGH) {
    result.waitList = list.filter(
      item => item.teacher_correct == TEACHER_CORRECT_TYPE.NO_CORRECT
    )
    result.finishList = list.filter(
      item => item.teacher_correct != TEACHER_CORRECT_TYPE.NO_CORRECT
    )
  } else {
    result.waitList = list.filter(item => item.score < 0)
    result.finishList = list.filter(item => item.score >= 0)
  }
  return result
}

const initData = () => {
  isAddingAnnotation.value = false
  getStudentMsgInfo()
  singleCorrectMitt.on('change-student-answer', param => {
    const { id } = param
    answerIndex.value = answerList.value.findIndex(
      item => item.student_id === id
    )
    isHistory.value = true
  })
}
watch(
  () => questionInfo.value,
  () => {
    if (questionInfo.value) {
      initData()
    }
  }
)
</script>

<style scoped lang="less">
@baseURL: '@/assets/images/single-correct';

.correction-container {
  width: calc(100vw - 280px);
  height: 100%;
  align-items: flex-start;
  .container-left {
    height: 100%;
    overflow-y: auto;
    overflow-x: hidden;
    padding-right: 10px;
    .tool-header {
      margin-bottom: 20px;
      .answer-img {
        width: 16px;
        height: 16px;
        margin: 0 4px;
        margin-right: 10px;
      }
      .remark {
        font-size: 24px;
        font-weight: bold;
        margin: 0 10px;
      }
      .remark-text {
        background-color: rgba(108, 208, 167, 0.3);
        color: #27ae61;
        font-size: 24px;
        margin-left: 20xp;
        border-radius: 30px;
        font-weight: bold;
        padding: 2px 16px;
      }
      .correct-control {
        gap: 10px;
        .header__button {
          flex: 0 0 auto;
          margin-left: 33px;
          border: 0;
          padding: 1px 0 0;
          outline: 0;
          background-color: transparent;
          background-repeat: no-repeat;
          background-position: left;
          line-height: 32px;
          font-size: 16px;
          font-weight: bold;
          color: #595959;
          cursor: pointer;
          &:disabled {
            color: #8c8c8c;
            opacity: 0.3;
            cursor: not-allowed;
          }
        }
        .btn-continue {
          padding-left: 30px;
          background-size: 22px 22px;
          background-image: url('@{baseURL}/btn-continue.png');
        }

        .btn-previous {
          padding-left: 18px;
          background-size: auto 20px;
          background-image: url('@{baseURL}/btn-previous.png');
        }

        .btn-next {
          padding: 1px 18px 0 0;
          background-size: auto 20px;
          background-image: url('@{baseURL}/btn-next.png');
          background-position: right;
        }
        .btn-reset-scale {
          padding: 0;
          width: 34px;
          height: 26px;
          background-image: url('@{baseURL}/btn-reset-scale.png');
          background-size: contain;
          cursor: pointer;

          &:disabled {
            background-image: url('@{baseURL}/btn-reset-scale-disabled.png');
            cursor: not-allowed;
          }
        }

        .btn-zoom-in {
          padding: 0;
          width: 25px;
          height: 29px;
          background-image: url('@{baseURL}/btn-zoom-in.png');
          background-size: contain;
          cursor: pointer;

          &:disabled {
            background-image: url('@{baseURL}/btn-zoom-in-disabled.png');
            cursor: not-allowed;
          }
        }

        .btn-zoom-out {
          padding: 0;
          width: 25px;
          height: 29px;
          background-image: url('@{baseURL}/btn-zoom-out.png');
          background-size: contain;
          cursor: pointer;

          &:disabled {
            background-image: url('@{baseURL}/btn-zoom-out-disabled.png');
            cursor: not-allowed;
          }
        }

        .btn-rotate {
          padding: 0;
          width: 31px;
          height: 31px;
          background-image: url('@{baseURL}/btn-rotate.png');
          background-size: contain;
          cursor: pointer;

          &:disabled {
            background-image: url('@{baseURL}/btn-rotate-disabled.png');
            cursor: not-allowed;
          }
        }
      }
      .img-control {
        margin-left: 30px;
        .header__button {
          margin-left: 10px;
        }
      }
    }
    .answer-container {
      .answer-text {
        background-color: #fff;
        padding: 20px;
        margin-top: 20px;
        word-wrap: break-word;
      }
      .empty-paper-tips {
        padding-top: 20px;
        align-items: center;
        gap: 20px;
        p {
          margin-top: 20px;
          font-size: 20px;
          font-weight: bold;
        }
        img {
          height: 600px;
          width: 600px;
        }
      }
    }
    .aside-score {
      flex-shrink: 0;
      margin: 16px 35px 0;
      height: 806px;
      border: 1px solid #d9d9d9;
      box-sizing: border-box;
      width: 338px;
      border-radius: 3px;
      background-color: #ffffff;
      display: flex;
      flex-direction: column;
      overflow: auto;
      &::-webkit-scrollbar {
        width: 0;
      }
    }
    .annotation-box {
      margin-top: 20px;
      :deep(.annotation-text-container) {
        background-color: #fff;
        .el-textarea__inner {
          background-color: #fff;
        }
      }
      .annotation-btn {
        .img {
          margin: -2px 4px 0 0;
        }
      }
    }
    width: calc(100% - 360px);
    margin-right: 12px;
  }
}
.score-board-disabled {
  cursor: not-allowed;
  pointer-events: none;
}
</style>

<!-- eslint-disable -->
<style lang="less">
.correction-popper {
  .topic-container {
    max-height: 70vh;
    overflow: auto;
  }
}
</style>
